<?php

class AuthController extends Zend_Controller_Action {

    public function indexAction() {
        $this->_forward('login');
    }

    public function logoutAction() {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_helper->redirector('login');
    }

    public function loginAction() {
        $this->view->application_env = APPLICATION_ENV;

        $frmLogin = new Application_Form_LoginForm();
        $this->view->frmLogin = $frmLogin;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if (isset($formData['submit_login']))
                if ($frmLogin->isValid($formData)) {
                    $username = $frmLogin->getValue('username');
                    $senha = $frmLogin->getValue('senha');
                    try {
                        $authAdapter = new Zend_Auth_Adapter_DbTable(Usuarios::getDefaultAdapter());
                        $authAdapter->setTableName('usuario');
                        $authAdapter->setIdentityColumn('username');
                        $authAdapter->setCredentialColumn('senha');
                        $authAdapter->setIdentity($username);
                        $authAdapter->setCredential(Usuarios::encrypt($senha));
                        $auth = Zend_Auth::getInstance();
                        $resultado = $auth->authenticate($authAdapter);

                        if ($resultado->isValid()) {
                            $dataAuth = $authAdapter->getResultRowObject(null, 'senha');
                            $auth->getStorage()->write($dataAuth);
                            $this->_forward('index', 'curso');
                        } else {
                            $session = Zend_Registry::get('session');
                            $session->erro = 'usuário => senha não conferem!';
                            $frmLogin->populate($formData);
                        }
                    } catch (Exception $e) {
                        Zend_Registry::set('message', $e->getMessage());
                    }
                } else {
                    $frmLogin->populate($formData);
                } 
        }
    }


    public function privilegesAction() {
        $session = Zend_Registry::get('session');
        $session->erro = 'Você não tem autorização para acessar este recurso!';
    }

}